from psycopg2 import pool
from psycopg2 import OperationalError


class PgsqlPool:
    def __init__(self, config):
        self.pool = None
        self.config = config
        self.init()

    def init(self):
        try:
            self.pool = pool.SimpleConnectionPool(
                minconn=2,                      # 最小连接数
                maxconn=10,                     # 最大连接数
                host=self.config['host'],            # 服务器
                port=self.config['port'],            # 端口
                user=self.config['user'],            # 用户名
                password=self.config['password'],    # 密码
                database=self.config['database'],    # 数据库
                keepalives=1,               # 不知道是啥
                keepalives_idle=30,         # 操作系统向客户端发送一个消息后无网络活动的时间
                keepalives_interval=10,     # 未被客户端确认收到的消息应重新传输的时间长度
                keepalives_count=5          # 指定服务器到客户端的连接被认为中断之前可以丢失的消息的数量
            )
        except Exception as err:
            self.pool = None
            print(err)

    def connect(self):
        # 如果pool为空,先恢复一下连接池
        if self.pool is None:
            self.init()

        # 恢复连接池失败
        if self.pool is None:
            return None, None

        conn = self.pool.getconn()
        cursor = conn.cursor()
        return conn, cursor

    def close(self, conn, cursor):
        if cursor is not None:
            cursor.close()
        if self.pool is not None:
            self.pool.putconn(conn)

    def close_all(self):
        if self.pool is not None:
            self.pool.closeall()

    def select(self, sql, one=False):
        conn, cursor = self.connect()
        if conn is None and cursor is None:
            return () if one else []

        try:
            cursor.execute(sql)
        except OperationalError:
            self.init()
            return () if one else []

        result = cursor.fetchone() if one else cursor.fetchall()
        self.close(conn, cursor)
        return result

    def execute(self, sql, value=None):
        conn, cursor = self.connect()
        if conn is None and cursor is None:
            return
        try:
            cursor.execute(sql, value)
            conn.commit()
            self.close(conn, cursor)
        except Exception as e:
            conn.rollback()
            print(e)
